package service

import (
	"encoding/json"
	"go-monitor/agent/g"
	"go-monitor/common/crypto"
	"go-monitor/common/model"
	"go-monitor/common/utility"
	"log"
	"os"
	"path/filepath"
)

var privateKey []byte
var publicKey []byte

var authdir string
var serverauthdir string

// InitAuth 获取密钥
func InitAuth() {
	var err error
	authdir := filepath.Join(g.Root+"/var/auth/client", "/")
	if utility.PathExists(authdir+"/private.pem") && utility.PathExists(authdir+"/public.pem") {
		privateKey, err = utility.ReadFileAsBytes(authdir + "/private.pem")
		if err != nil {
			g.Logger.Error("create privateKey fail:", err)
		}
		publicKey, err = utility.ReadFileAsBytes(authdir + "/public.pem")
		if err != nil {
			g.Logger.Error("create publicKey fail:", err)
		}
	} else {
		if !utility.PathExists(authdir) {
			err := os.MkdirAll(authdir, os.ModeDir)
			if err != nil {
				g.Logger.Error("auth client dir create fail:", err)
			}
			crypto.GenRsaKey(512, authdir+"/")
			privateKey, err = utility.ReadFileAsBytes(authdir + "/private.pem")
			if err != nil {
				g.Logger.Error("create privateKey fail:", err)
			}
		}
		serverauthdir := filepath.Join(g.Root+"/var/auth/server", "/")
		if !utility.PathExists(serverauthdir) {
			err := os.MkdirAll(serverauthdir, os.ModeDir)
			if err != nil {
				g.Logger.Error("auth server dir create fail:", err)
			} else {
				publicKey, err = utility.ReadFileAsBytes(authdir + "/public.pem")
				if err != nil {
					g.Logger.Error("create publicKey fail:", err)
				}
			}
		}
	}
}

// AuthLogin Server通信，Agent身份认证
func AuthLogin() {
	var aar model.AgentAuthRequest
	aar.ID = g.IP()
	aar.IP = g.IP()
	aar.AgentVersion = g.VERSION
	aar.ClientKey = publicKey

	var srr model.SimpleRPCResponse

	err := g.RPCClient.Call("Server.Auth", aar, &srr)
	if err != nil {
		log.Println("AuthLogin fail:", err)
		g.Logger.Error("AuthLogin fail:", err)
	}

	if srr.Code == 0 {
		log.Println("AuthLogin Ok:", srr.Message)
		g.Logger.Info("AuthLogin Ok:", srr.Message)
	}

	if srr.Code == 1 {
		log.Println("AuthLogined", srr.Message)
		g.Logger.Info("AuthLogined", srr.Message)
	}
}

// 加密
func RsaEncrypt(origData []byte) ([]byte, error) {
	return crypto.RsaEncrypt(origData, publicKey)
}

// 解密
func RsaDecrypt(ciphertext []byte) ([]byte, error) {
	return crypto.RsaDecrypt(ciphertext, privateKey)
}

//验证签名
func CheckSign(data []byte, req interface{}) bool {
	rbyte, err := json.Marshal(req)
	if err == nil {
		sign, err := crypto.RsaDecrypt(data, privateKey)
		if err != nil {
			g.Logger.Error("验证签名(CheckSign):", err)
			return false
		}
		if string(sign) != utility.GetMd5String(string(rbyte)) {
			return false
		} else {
			return true
		}
	}
	return false
}
